package src.反射4;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflectionDemo {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        //不适用反射
        Teacher teacher = new Teacher();
        String typeInstanceof = getTypeInstanceof(teacher);
        System.out.println("typeInstanceof = " + typeInstanceof);

        //测试反射方式
        Student student = new Student();
        String type = getType(student);
        System.out.println("type = " + type);
    }

    public static String getTypeInstanceof(Object obj) {
        //学生
        if (obj instanceof Student) {
            Student student = (Student) obj;
            String userType = student.getUserType("小雪");
            return userType;
        }

        //老师
        if (obj instanceof Teacher){
            Teacher teacher=(Teacher) obj;
            String userType = teacher.getUserType("李莉莉");
            return userType;
        }
        return null;
    }

     public static String getType(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //1.得到反射类对象
         Class<?> aClass = obj.getClass();
         //2.确定反射类对象
         Object instance = aClass.newInstance();
         Method getUserType = aClass.getMethod("getUserType", String.class);
         String invoke = (String) getUserType.invoke(instance, "王晓晓");
         return invoke;
     }
}
